package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Transactional
@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer id = setmeal.getId();
        setSetmealAndtCheckGroup(id, checkgroupIds);
        //获取图片的名称
        String img = setmeal.getImg();
        if (img != null && img.length() > 0 && img != "") {
            //将图片的名称使用set方式保存到Redis数据库(套餐图片保存在数据库中的图片名称)
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
        }
        //调用模板重新生成静态页面
        generateMobileStaticHtml(id);
    }

    //根据id生成静态页面
    public void generateMobileStaticHtml(Integer setmealId) {
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setmealDao.findAll();
        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);
        if (setmealId != null && setmealId != 0) {
            //需要生成套餐详情静态页面
            generateMobileSetmealDetailHtml(setmealId);
        } else {
            generateMobileSetmealDetailHtml(list);
        }
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map map = new HashMap();
        map.put("setmealList", list);
        generteHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    //生成套餐详情静态页面（可能有多个）
    public void generateMobileSetmealDetailHtml(Integer setmealId) {
        Map map = new HashMap();
        map.put("setmeal", setmealDao.findById(setmealId));
        generteHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmealId + ".html", map);
    }

    //生成套餐详情静态页面（可能有多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            Setmeal detail = setmealDao.findById(setmeal.getId());
            map.put("setmeal", detail);
            generteHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    //模板文件
    public void generteHtml(String templateName, String htmlPageName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer writer = null;
        try {
            //加载模板文件
            Template template = configuration.getTemplate(templateName);
            //准备输出流对象，用于输出静态文件
            writer = new FileWriter(outPutPath + "/" + htmlPageName);
            //输出
            template.process(map, writer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关流
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
        return setmealDao.findCheckItemIdsByCheckGroupId(id);
    }

    @Override
    public void edit(Integer[] checkgroupIds, Setmeal setmeal, String updateUrl) {
        setmealDao.edit(setmeal);
        int index = updateUrl.lastIndexOf("/");
        updateUrl = updateUrl.substring(index + 1);
        String img = setmeal.getImg();
        //判断修改前数据是否存在图片并且是否修改了图片
        if (updateUrl != null && updateUrl != "" && updateUrl.length() > 0 && updateUrl != img) {
            //修改了图片将以前保存的图片删除掉(套餐图片保存在数据库中的图片名称)
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, updateUrl);
        }
        if (img != null && img.length() > 0 && img != "") {
            //将修改后的图片保存(套餐图片保存在数据库中的图片名称)
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
        }
        setmealDao.deleteAssocication(setmeal.getId());
        Integer id = setmeal.getId();
        setSetmealAndtCheckGroup(id, checkgroupIds);
        //调用模板重新生成静态页面
        generateMobileStaticHtml(id);
    }

    @Override
    public void delete(Integer id) {
        //删除中间表对应的数据
        setmealDao.deleteAssocication(id);
        Setmeal setmeal = setmealDao.findById(id);
        String img = setmeal.getImg();
        //删除数据
        Boolean flag = setmealDao.delete(id);
        if (flag) {
            //删除redis数据库对应的图片
            jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
        }
        //调用模板重新生成静态页面
        generateMobileStaticHtml(id);
    }

    //查询所有的图片名字
    //暂时没用
    @Override
    public List<String> findAllImg() {
        return setmealDao.findAllImg();
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    public void setSetmealAndtCheckGroup(Integer id, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("id", id);
                map.put("checkgroupId", checkgroupId);
                setmealDao.setSetmealAndtCheckGroup(map);
            }
        }
    }
}
